import {multiUpload,singleUpload} from "../../utils/tools";

import {
	add,
	get
} from "../../utils/db";
const db = wx.cloud.database()

Page({
	data: {
		list: [], //音频列表
		typeIndex:0,	//分类下标
		typeList: [], //分类列表
		coverImage: "/images/add.png",
		intro: "", //图书简介
	},
	onLoad() {
		this.getList()

		//获取分类列表
		this.getTypeList()
	},
	//选择分类
	selectType(e) {
		var index = e.detail.value; //下标
		this.setData({
			typeid: this.data.typeList[index]._id,
			typeIndex:index
		})
	},
	//获取分类列表
	async getTypeList() {
		var result = await get({
			collection: "type",
			where: {
				status: 1
			}
		}).catch(err => {
			console.error(err)
		})
		this.setData({
			typeList: result.data
		})
	},
	//获取图书列表
	getList() {
		db.collection("book").where({
				status: 1
			}).orderBy('addtime', 'desc')
			.get()
			.then(res => {
				this.setData({
					bookList: res.data
				})
			})
	},
	//添加图片
	addPic() {
		wx.chooseImage({
			count: 1,
			success: (res => {
				this.setData({
					coverImage: res.tempFilePaths[0]
				})
			})
		})
	},
	//写入简介时触发
	myEditorInput(e) {
		this.data.intro = e.detail.html;
	},
	//选择音频
	chooseAudio() {
		wx.chooseMessageFile({
			count: 100,
			type: "file",
			success: res => {
				this.setData({
					list: res.tempFiles
				})

			},
			fail: err => {
				console.error(err)
			}
		})
	},
	//提交表单
	async handleSubmit(e) {
		let {bookName,author,speaker,typeid,subName} = e.detail.value
		if (bookName == "" ||subName==""|| typeid == "" || author == "" || speaker == "" || this.data.images == "/images/add.png" || this.data.intro == "") {
			wx.showToast({
				title: "表单数据不全",
				icon: "none"
			})
			return;
		}
		if (this.data.list.length == 0) {
			wx.showModal({
				title: "请添加音频文件",
				icon: "none"
			})
			return;
		}
		wx.showLoading({
			title: '正在提交',
		})
		//上传封面
		var result = await singleUpload(this.data.coverImage);
		var fileids = [];
		fileids.push(result.fileID)
		//添加图书信息到数据库
		var bookData = {
			bookName,
			typeid,
			author,
			speaker,
			intro: this.data.intro,
			fileids,
			subName,
			addtime: new Date().getTime(),
			status: 1
		}
		var result = await add({
			collection: "book",
			data: bookData
		}).catch(err => console.error(err))
		var bookId = result._id; //获取图书id

		//上传音频文件
		var result = await multiUpload(this.data.list).catch(err => console.error(err))
		console.log(result,"1111")

		//添加数据库
		result.forEach(async (item, index) => {
			var audioPath = item.fileID;
			var audioName = this.data.list[index].name;
			var addtime = new Date().getTime()
			var status = 1

			var formData = {
				bookId,
				bookName,
				audioPath,
				audioName,
				addtime,
				status
			}
			//添加音频信息到数据库
			var result = await add({
				collection: "audio",
				data: formData
			}).catch(err => console.error(err))
		})

		wx.hideLoading() //提交完成，隐藏loading
		wx.showModal({
			title: "温馨提示",
			content: "成功上传"
		})


	}
})